package com.sit.estatemanagementserver.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Base64;

@Service
public class SignatureService {

    @Autowired
    private KeyPair keyPair;

    private static final String SIGNING_ALGORITHM = "SHA256withRSA";

    public String sign(String data) {
        try {
            Signature privateSignature = Signature.getInstance(SIGNING_ALGORITHM);
            privateSignature.initSign(keyPair.getPrivate());
            privateSignature.update(data.getBytes(StandardCharsets.UTF_8));
            byte[] signature = privateSignature.sign();
            return Base64.getEncoder().encodeToString(signature);
        } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException e) {
            throw new RuntimeException("Could not sign data", e);
        }
    }
}